import store from '@/store'

const progress = {
  percentage: 0,
  timer: 0,
  complete: false
}

function Init(percentage = 0) {
  Update(percentage)
}

function Add(val) {
  Update(progress.percentage + val)
}

function Update(percentage) {
  progress.percentage = percentage
  if (progress.percentage > 100) progress.percentage = 100
  store.dispatch('editor/diagram/updateProgress', progress.percentage)
}

function SetError(err) {
  store.dispatch('editor/diagram/setProgressError', err)
}

function Start(step = 10, timeout = 300) {
  progress.percentage = 0
  progress.complete = false
  clearInterval(progress.timer)
  // 启动定时器
  progress.timer = setInterval(() => {
    if (progress.complete) {
      progress.percentage = 100
    } else if (progress.percentage + step > 100) {
      progress.percentage = parseInt(0.618 * (progress.percentage + step))
    } else {
      progress.percentage += step
    }
    Update(progress.percentage)
  }, timeout)
}

function Complete(err = null) {
  // 关闭定时器
  clearInterval(progress.timer)
  progress.timer = 0
  if (err) {
    // 设置错误信息
    SetError(err)
  } else {
    Update(100)
  }
  progress.complete = true
}

export default {
  Start,
  Complete,
  Init,
  Update,
  SetError,
  Add
}
